package cn.pku.sirx.snad.mss.web.article;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.ParameterizableViewController;

import cn.pku.sirx.snad.ad.Constants;
import cn.pku.sirx.snad.mss.domain.IArticleFacade;
import cn.pku.sirx.snad.mss.domain.IUserFacade;
import cn.pku.sirx.snad.mss.model.entity.Article;
import cn.pku.sirx.snad.mss.model.entity.SiteUser;

/**
 * @author WangXiao
 */
public class ArticleController extends ParameterizableViewController {

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		/*
		 * handle ID
		 */
		String requestUserId = request.getParameter("idInput");
		if (requestUserId == null) {
			requestUserId = (String) request.getSession().getAttribute(
					Constants.WEB_P_USER_ID);
			if (requestUserId == null) {
				requestUserId = defaultUserId;
			}
		}
		request.getSession().setAttribute(Constants.WEB_P_USER_ID,
				requestUserId);
		/*
		 * get model
		 */
		SiteUser user = userFacade.get(requestUserId);
		Article article = articleFacade.getRandomArticle();
		return super.handleRequestInternal(request, response).addObject("user",
				user).addObject("article", article).addObject("userIp",
				request.getRemoteAddr());
	}

	private String defaultUserId = "50574";

	private IUserFacade userFacade;
	private IArticleFacade articleFacade;

	public void setUserFacade(IUserFacade userFacade) {
		this.userFacade = userFacade;
	}

	public void setArticleFacade(IArticleFacade articleFacade) {
		this.articleFacade = articleFacade;
	}

}
